<template>
  <div class="user-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <div class="search-bar">
        <el-form :model="searchForm" inline>
          <el-form-item label="用户名">
            <el-input 
              v-model="searchForm.userName" 
              placeholder="请输入用户名" 
              clearable 
              @keyup.enter="handleSearch"
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="工号">
            <el-input 
              v-model="searchForm.opNum" 
              placeholder="请输入工号" 
              clearable 
              @keyup.enter="handleSearch"
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              🔍 搜索
            </el-button>
            <el-button @click="handleReset">
              🔄 重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 主体内容区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">👥 用户管理</span>
          <div class="header-actions">
            <div class="record-stats">
              <el-tag type="info">共 {{ total }} 个用户</el-tag>
            </div>
            <div class="action-buttons">
              <el-button type="success" @click="handleExport" :loading="exportLoading">
                📤 导出数据
              </el-button>
              <el-button type="primary" @click="handleAdd" :icon="Plus">
                ➕ 新增用户
              </el-button>
            </div>
          </div>
        </div>
      </template>
      
      <div class="table-container">
        <el-table 
          :data="tableData" 
          style="width: 100%" 
          v-loading="loading"
          :height="tableHeight"
          class="custom-table"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="userName" label="用户名" width="150" show-overflow-tooltip />
          <el-table-column prop="realName" label="真实姓名" width="120" show-overflow-tooltip />
          <el-table-column prop="email" label="邮箱" width="200" show-overflow-tooltip />
          <el-table-column prop="phone" label="手机号" width="130" show-overflow-tooltip />
          <el-table-column prop="opNum" label="工号" width="120" show-overflow-tooltip />

          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="200" align="center" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                ✏️ 编辑
              </el-button>
              <el-button type="warning" size="small" @click="handleResetPassword(row)">
                🔑 重置密码
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                🗑️ 删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pageCurrent"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑用户弹窗 -->
    <el-dialog
      v-model="showUserModal"
      :title="isEdit ? '✏️ 编辑用户' : '➕ 新增用户'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="120px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="工号" prop="opNum">
          <el-input v-model="userForm.opNum" placeholder="请输入工号" :disabled="isEdit" />
        </el-form-item>

        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeUserModal">取消</el-button>
          <el-button type="primary" @click="confirmUser" :loading="confirmLoading">
            {{ confirmLoading ? '保存中...' : '确定' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重置密码弹窗 -->
    <el-dialog
      v-model="showPasswordModal"
      title="🔑 重置密码"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="120px">
        <el-form-item label="用户名">
          <el-input v-model="passwordForm.userName" disabled />
        </el-form-item>
        <el-form-item label="原密码" prop="password">
          <el-input v-model="passwordForm.password" type="password" placeholder="请输入原密码" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="passwordNew">
          <el-input v-model="passwordForm.passwordNew" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closePasswordModal">取消</el-button>
          <el-button type="primary" @click="confirmPassword" :loading="passwordLoading">
            {{ passwordLoading ? '修改中...' : '确定' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { queryUserListPage, addUser, updateUser, deleteUser, exportUserData, editUserPassword } from '../api/business.js'

// 响应式数据
const loading = ref(false)
const exportLoading = ref(false)
const tableData = ref([])
const total = ref(0)
const pageSize = ref(10)
const pageCurrent = ref(1)

// 搜索表单
const searchForm = reactive({
  userName: '',
  opNum: ''
})

// 弹窗相关
const showUserModal = ref(false)
const showPasswordModal = ref(false)
const isEdit = ref(false)
const confirmLoading = ref(false)
const passwordLoading = ref(false)
const userFormRef = ref()
const passwordFormRef = ref()

// 用户表单
const userForm = reactive({
  id: null,
  userName: '',
  realName: '',
  email: '',
  phone: '',
  opNum: '',
  role: 0,
  password: ''
})

// 密码表单
const passwordForm = reactive({
  id: null,
  userName: '',
  password: '',
  passwordNew: ''
})

// 表单验证规则
const userRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],

  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 密码表单验证规则
const passwordRules = {
  password: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  passwordNew: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 加载管理器
let loadingInstance = null
const showLoading = (text = '加载中...') => {
  if (loadingInstance) {
    loadingInstance.close()
  }
  loadingInstance = ElLoading.service({
    lock: true,
    text: text,
    background: 'rgba(0, 0, 0, 0.7)'
  })
}

const hideLoading = () => {
  if (loadingInstance) {
    loadingInstance.close()
    loadingInstance = null
  }
}

// 计算表格高度
const tableHeight = computed(() => {
  return 'calc(100vh - 280px)'
})

// 获取用户列表数据
const getData = async () => {
  loading.value = true
  
  try {
    const params = {
      pageNum: pageCurrent.value,
      pageSize: pageSize.value,
      userName: searchForm.userName || undefined,
      opNum: searchForm.opNum || undefined
    }
    
    const res = await queryUserListPage(params)
    console.info('用户列表数据:', res)
    
    if (res && res.success === true && res.content) {
      tableData.value = res.content.list || []
      total.value = res.content.total || 0
      
      ElMessage.success(`👥 成功获取${tableData.value.length}个用户`)
    } else {
      throw new Error(res?.message || '数据格式错误')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error(error.data?.message || '获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  getData()
}

const handleCurrentChange = (page) => {
  pageCurrent.value = page
  getData()
}

// 搜索处理
const handleSearch = () => {
  pageCurrent.value = 1
  getData()
}

const handleReset = () => {
  searchForm.userName = ''
  searchForm.opNum = ''
  pageCurrent.value = 1
  getData()
}

// 重置表单
const resetUserForm = () => {
  userForm.id = null
  userForm.userName = ''
  userForm.realName = ''
  userForm.email = ''
  userForm.phone = ''
  userForm.opNum = ''
  userForm.role = 0
  userForm.password = ''
}

// 新增用户
const handleAdd = () => {
  isEdit.value = false
  resetUserForm()
  showUserModal.value = true
}

// 编辑用户
const handleEdit = (row) => {
  isEdit.value = true
  userForm.id = row.id
  userForm.userName = row.userName || ''
  userForm.realName = row.realName || ''
  userForm.email = row.email || ''
  userForm.phone = row.phone || ''
  userForm.opNum = row.opNum || ''
  userForm.role = row.role || 0
  userForm.password = '' // 编辑时不显示密码
  showUserModal.value = true
}

// 导出用户数据
const handleExport = async () => {
  try {
    exportLoading.value = true
    showLoading('导出中...')
    
    // 构建导出参数
    const exportParams = {}
    if (searchForm.userName) {
      exportParams.userName = searchForm.userName
    }
    if (searchForm.opNum) {
      exportParams.opNum = searchForm.opNum
    }
    
    // 调用导出API，token会自动在header中传递
    const response = await exportUserData(exportParams)
    
    // 检查响应是否为blob
    if (response instanceof Blob) {
      // 创建下载链接
      const url = window.URL.createObjectURL(response)
      const link = document.createElement('a')
      link.href = url
      link.download = `用户数据_${new Date().toISOString().slice(0, 10)}.xlsx`
      link.style.display = 'none'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      hideLoading()
      ElMessage.success('📤 导出成功')
    } else {
      throw new Error('导出数据格式错误')
    }
    
  } catch (error) {
    hideLoading()
    console.error('导出失败:', error)
    
    // 如果是网络错误，提供更详细的错误信息
    if (error.code === 'ERR_INCOMPLETE_CHUNKED_ENCODING') {
      ElMessage.error('❌ 导出失败：数据传输中断，请重试')
    } else if (error.message && error.message.includes('timeout')) {
      ElMessage.error('❌ 导出超时，请重试')
    } else {
      ElMessage.error('❌ ' + (error.message || error.data?.message || '导出失败'))
    }
  } finally {
    exportLoading.value = false
  }
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 "${row.userName}" 吗？删除后无法恢复。`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    showLoading('删除中...')
    
    const res = await deleteUser([row.id])
    
    hideLoading()
    
    if (res && res.success === true) {
      ElMessage.success('✅ 删除成功')
      
      // 刷新列表
      setTimeout(() => {
        getData()
      }, 500)
    } else {
      throw new Error(res?.message || '删除失败')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      hideLoading()
      console.error('删除用户失败:', error)
      ElMessage.error('❌ ' + (error.message || error.data?.message || '删除失败'))
    }
  }
}

// 关闭弹窗
const closeUserModal = () => {
  showUserModal.value = false
  resetUserForm()
  if (userFormRef.value) {
    userFormRef.value.clearValidate()
  }
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.id = null
  passwordForm.userName = ''
  passwordForm.password = ''
  passwordForm.passwordNew = ''
}

// 重置密码
const handleResetPassword = (row) => {
  resetPasswordForm()
  passwordForm.id = row.id
  passwordForm.userName = row.userName || ''
  showPasswordModal.value = true
}

// 关闭密码弹窗
const closePasswordModal = () => {
  showPasswordModal.value = false
  resetPasswordForm()
  if (passwordFormRef.value) {
    passwordFormRef.value.clearValidate()
  }
}

// 确认修改密码
const confirmPassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    
    passwordLoading.value = true
    showLoading('修改密码中...')
    
    const passwordData = {
      id: passwordForm.id,
      userName: passwordForm.userName,
      password: passwordForm.password,
      passwordNew: passwordForm.passwordNew
    }
    
    const res = await editUserPassword(passwordData)
    
    hideLoading()
    
    if (res && res.success === true) {
      ElMessage.success('🔑 密码修改成功')
      closePasswordModal()
    } else {
      throw new Error(res?.message || '密码修改失败')
    }
    
  } catch (error) {
    hideLoading()
    if (error.message && error.message.includes('请输入')) {
      // 表单验证错误，不显示错误消息
      return
    }
    
    console.error('修改密码失败:', error)
    ElMessage.error('❌ ' + (error.message || error.data?.message || '密码修改失败'))
  } finally {
    passwordLoading.value = false
  }
}

// 确认保存用户
const confirmUser = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    
    confirmLoading.value = true
    showLoading(isEdit.value ? '更新中...' : '保存中...')
    
    const userData = {
      userName: userForm.userName,
      realName: userForm.realName,
      email: userForm.email,
      phone: userForm.phone,
      opNum: userForm.opNum,
      role: userForm.role
    }
    
    // 新增时需要密码
    if (!isEdit.value) {
      userData.password = userForm.password
    }
    
    let res
    if (isEdit.value) {
      userData.id = userForm.id
      res = await updateUser(userData)
    } else {
      res = await addUser(userData)
    }
    
    hideLoading()
    
    if (res && res.success === true) {
      ElMessage.success(isEdit.value ? '✅ 更新成功' : '✅ 新增成功')
      closeUserModal()
      
      // 刷新列表
      setTimeout(() => {
        getData()
      }, 500)
    } else {
      throw new Error(res?.message || (isEdit.value ? '更新失败' : '新增失败'))
    }
    
  } catch (error) {
    hideLoading()
    if (error.message && error.message.includes('请输入')) {
      // 表单验证错误，不显示错误消息
      return
    }
    
    console.error('保存用户失败:', error)
    ElMessage.error('❌ ' + (error.message || error.data?.message || '保存失败'))
  } finally {
    confirmLoading.value = false
  }
}

// 组件挂载时初始化
onMounted(() => {
  getData()
})
</script>

<style scoped>
.user-management {
  background: #f5f7fa;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-bar {
  display: flex;
  align-items: center;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  padding-bottom: 70px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.card-title {
  font-size: 18px;
  font-weight: 700;
  color: #1e40af;
}

.header-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  flex: 1;
}

.search-section {
  display: flex;
  align-items: center;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.record-stats {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-container {
  flex: 1;
  overflow: hidden;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.custom-table {
  width: 100%;
  flex: 1;
}

.pagination {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  background: #ffffff;
  border-top: 1px solid #e4e7ed;
  z-index: 10;
}

/* 表格滚动条样式 */
:deep(.el-table) {
  height: 100% !important;
}

:deep(.el-table__body-wrapper) {
  /* 只在需要时显示滚动条 */
  overflow-y: auto !important;
  overflow-x: hidden !important;
  max-height: calc(100vh - 350px) !important;
  /* 为底部分页器预留更多空间，避免遮挡 */
  padding-bottom: 10px !important;
}

/* 滚动条样式优化 */
:deep(.el-table__body-wrapper)::-webkit-scrollbar {
  width: 8px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f5f5f5;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
  transition: background 0.3s ease;
  min-height: 20px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-corner {
  background: #f5f5f5;
}

/* 表格横向铺满 */
:deep(.el-table) {
  width: 100% !important;
  min-width: 100% !important;
}

:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__footer-wrapper) {
  width: 100% !important;
}

/* 确保表格内容不会超出容器 */
:deep(.el-table__header),
:deep(.el-table__body) {
  width: 100% !important;
  table-layout: fixed;
}

/* 表格单元格内容溢出处理 */
:deep(.el-table .cell) {
  word-break: break-word;
  word-wrap: break-word;
  white-space: normal;
  line-height: 1.4;
}

/* 确保最后一行数据不被遮挡 */
:deep(.el-table__body tr:last-child td) {
  border-bottom: 1px solid #ebeef5;
}

/* 弹窗样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-management {
    padding: 16px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .action-buttons {
    width: 100%;
    justify-content: flex-end;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}
</style>